# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
import datetime
import logging
import base64
from utils import get_client, get_json

from google.appengine.ext import db
from ragendja.dbutils import get_object, db_create

class SNSBackend(ModelBackend):
    def authenticate(self, request):
        try:
            today = datetime.date.today()
            now = datetime.datetime.now()
            client = get_client(request)
            if client.name == 'xn':
                info = client.getUsersInfo(fields = ['name', 'tinyurl', 'headurl', 'sex', 'zidou', 'university_history'])
                try:
                    university = info[0]['university_history'][0]['name']
                except:
                    university = ''
                defaults={'username': str(info[0]['uid']),
                          'nickname': info[0]['name'],
                          'tinyurl': info[0]['tinyurl'],
                          'headurl': info[0]['headurl'],
                          'sex': str(info[0]['sex']),
                          'zidou': str(info[0]['zidou']),
                          'university': university,
                          }
                uid = str(info[0]['uid'])
                logging.info(u"%s" % defaults)
                user = get_object(User, 'uid =', uid, 'origin =', 'xiaonei')
                if not user:
                    user = db_create(User, uid=uid, origin = 'xiaonei', username = uid)
                    
                user.nickname = defaults['nickname']
                user.tinyurl = defaults['tinyurl']
                user.loc = defaults['university']
                user.sex = defaults['sex']
                user.zidou = defaults['zidou']
                user.headurl = defaults['headurl']
                user.info_updated = now
                user.put()
            elif client.name == '51':
                logging.info(u"checked %s" % client.checked)
                if client.checked:
                    username = request.REQUEST['51_sig_user']
                    user = get_object(User, 'username =', username, 'origin =', '51')
                    if not user:
                        user = db_create(User, username=username, origin = '51',)
                        created = True
                    else:
                        created = False
                    if created or user.info_updated.date() != today:
                        info = client.getUsersInfo(uids = [request.REQUEST['51_sig_user'],], fields = ['uid', 'username', 'nickname', 'sex', 'vip', 'city', 'facesmall', 'face'])
                        logging.info(u"%s" % info)
                        defaults={'uid': info[0]['username'],
                                  'nickname': base64.standard_b64decode(info[0]['nickname']).decode('utf-8'),
                                  'tinyurl': info[0]['facesmall'],
                                  'headurl': info[0]['face'],
                                  'sex': info[0]['sex'],
                                  'zidou': str(info[0]['vip']),
                                  'loc': info[0]['city'],
                                  }
                        logging.info(u"%s" % defaults)
                        user.uid = defaults['uid']
                        user.nickname = defaults['nickname'] or info[0]['username']
                        user.tinyurl = defaults['tinyurl']
                        user.loc = defaults['loc']
                        user.sex = defaults['sex']
                        user.zidou = defaults['zidou']
                        user.headurl = defaults['headurl']
                        user.info_updated = now
                        user.put()
                else:
                    return None
    
            return user
        except Exception,e:
            logging.error(u"Exception in authenticate %s" % e)
            return None